package utilities;

import com.google.gson.*;

public class JsonUtils {
	
	private static final GsonBuilder _builder = new GsonBuilder();
	
	/**
	 * Converts the srcObject to a json according to the type adapter.
	 * Uses this method if the srcObject inherits from another class and on the deserialization you don't
	 * know the type of the class. 
	 * @param <T> - The type of the serialized object (same as the baseType).
	 * @param srcObject - The srcObject that will be convert to json. 
	 * @param baseType - The base type of the srcObject class.
	 * @param typeAdapter - The type adapter of the srcObject. (needed to be created by the user.
	 * @return - The srcObject as json.
	 */
	public static <T> String toJson(Object srcObject, Class<T> baseType, Object typeAdapter){

		Gson gson = _builder.registerTypeHierarchyAdapter(baseType, typeAdapter).create();
		
		return gson.toJson(srcObject);
	}
	
	/**
	 * Converts the srcObject to a json.
	 * @param srcObject - The object that will be convert to json.
	 * @return - The srcObject as json.
	 */
	public static String toJson(Object srcObject){
		
		Gson gson = _builder.create();
		
		return gson.toJson(srcObject);
	}
	
	/**
	 * Converts the json to object.
	 * Uses this methods if the inherited type is unknown on deserialization.
	 * @param <T> - The type of the serialized object (same as the baseType).
	 * @param srcJson
	 * @param baseType - The base type of the srcObject class.
	 * @param typeAdapter - The type adapter of the srcObject. (needed to be created by the user.
	 * @return - The json as Object
	 */
	public static <T>T fromJson(String srcJson, Class<T> baseType, Object typeAdapter){
		Gson gson = _builder.registerTypeHierarchyAdapter(baseType, typeAdapter).create();
		
		return gson.fromJson(srcJson, baseType);
	}
	
	/**
	 * Converts the json to object.
	 * @param <T> - The type of the serialized object (same as the baseType).
	 * @param srcJson
	 * @param baseType - The type of the object
	 * @return - The json as object
	 */
	public static <T>T fromJson(String srcJson, Class<T> baseType){
		Gson gson = _builder.create();
		
		return gson.fromJson(srcJson, baseType);
	}
}
